import os
import logging
from logging.handlers import TimedRotatingFileHandler

from application.config import appSettings as config


class MyLogger:
    def __init__(self, logname='sanren'):
        log_path = os.path.join(config.log_path, 'sanren')

        # 日志目录
        if not os.path.exists(log_path):
            os.makedirs(log_path)

        # 日志格式
        formatter = logging.Formatter('[%(asctime)s] [%(filename)s:%(lineno)d] [%(levelname)s] [%(thread)d] - %(message)s')

        # 创建 Logger
        self.logger = logging.getLogger(logname)
        self.logger.setLevel(logging.DEBUG)

        # 日志按天记录
        log_file = os.path.join(log_path, f'{logname}.log')
        handler = TimedRotatingFileHandler(log_file, when='D', interval=1, backupCount=7, encoding='UTF-8', delay=False, utc=True)
        handler.setFormatter(formatter)

        # 添加 handler
        self.logger.addHandler(handler)


__all__ = [
    'MyLogger'
]
